﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using Prism.Commands;
using Prism.Events;
using System.Windows.Input;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using SoonCode.Core;
using SoonCode.FocusTest.Events;
using SoonCode.FocusTest.Models;
using SoonCode.FocusTest.Utils;
using SoonCode.FocusTest.Views;

namespace SoonCode.FocusTest.ViewModels
{
    internal class TestItemGViewModel:BindableBase
    {
        private int TestItemIndex = 7;
        private string itemType = "itemG";
        private int tabIndex = 0;
        private int err = 0;
        private TestInfo testInfo;
        private IEventAggregator aggregator;
        private SubscriptionToken answerToken;
        private IDialogService dialogService;
        private int level = 1;
        private int question = 1;
        private string levelImage = "";
        private string helpSoundText = "停止播放提示语";
        private bool helpIsPlay = true;
        public string HelpSoundText
        {
            get { return helpSoundText; }
            set
            {
                helpSoundText = value;
                RaisePropertyChanged();
            }
        }

        public int Question
        {
            get { return question; }
            set
            {
                question = value;
                RaisePropertyChanged();
            }
        }
        public string LevelImage
        {
            get { return levelImage; }
            set
            {
                levelImage=value;
                RaisePropertyChanged();
            }
        }
        public int Level
        {
            get { return level; }
            set
            {
                level = value;
                RaisePropertyChanged();
            }
        }

        public TestItemGViewModel(IEventAggregator aggregator,IDialogService dialogService)
        {
            this.aggregator = aggregator;
            this.dialogService = dialogService;
            aggregator.GetEvent<EndTestEvent>().Subscribe(() =>
            {
                aggregator.GetEvent<StudentAnswerEvent>().Unsubscribe(answerToken);
            });
            aggregator.GetEvent<TestLoadEvent>().Subscribe(OnLoaded);
        }

        private void OnLoaded(int p)
        {
            if (p != this.TestItemIndex - 1)
            {
                if (answerToken != null)
                    aggregator.GetEvent<StudentAnswerEvent>().Unsubscribe(answerToken);
                return;
            }
            this.testInfo = GlobalModel.Instance.TestInfo;
            TabIndex = 0;
            Level = 1;
            Question = 1;
            err = 0;
            levelImage = "";
            answerToken = aggregator.GetEvent<StudentAnswerEvent>().Subscribe(SutdentAnswer);
            SoundPlayer.Play("1000:item7.mp3");
        }

        private void SutdentAnswer(EventInfo payload)
        {
            if (payload == null || payload.Type!=itemType+"_submit")
            {
                return;
            }

            bool p = (bool)payload.Data["collision"];
            if (p)
            {
                err++;
            }
            NextTest();
        }
        public int TabIndex
        {
            get { return tabIndex; }
            set
            {
                tabIndex = value;
                RaisePropertyChanged();
            }
        }
        public ICommand HelpCommand
        {
            get
            {
                return new DelegateCommand(() =>
                {
                    if (helpIsPlay)
                    {
                        SoundPlayer.Stop();
                        HelpSoundText = "播放提示语";
                        helpIsPlay = false;
                    }
                    else
                    {
                        SoundPlayer.Play("item7.mp3");
                        HelpSoundText = "停止播放提示语";
                        helpIsPlay = true;
                    }
                });
            }
        }
        public ICommand SkipCommand
        {
            get
            {
                return new DelegateCommand(() =>
                {
                    this.aggregator.GetEvent<ChangeTestEvent>().Publish(TestItemIndex);
                });
            }
        }
        public ICommand StartCommand
        {
            get
            {
                return new DelegateCommand(() =>
                {
                    TabIndex = 1;
                    SoundPlayer.Stop();
                    EventInfo info = new EventInfo();
                    info.Type = itemType;
                    this.aggregator.GetEvent<StudentStartTestEvent>().Publish(info);
                    int age = GlobalModel.Instance.MemberInfo.age;
                    if (age < 9) Level = 1;
                    else if(age==9) Level = 3;
                    else if (age > 9) Level = 4;
                    Test();
                });
            }
        }

        public ICommand AnswerErrorCommand
        {
            get
            {
                return new DelegateCommand(() =>
                {
                    err++;
                    NextTest();
                });
            }
        }
        public ICommand AnswerRightCommand
        {
            get
            {
                return new DelegateCommand(() =>
                {
                    NextTest();
                });
            }
        }

        public void NextTest()
        {
            if (err >= 2)
            {
                if (Question == 2) err++;
                complete();
                return;
            }
            if (Question >= 3||(err==0&&Question>=2))
            {
                Level++;
                err = 0;
                Question = 1;
            }
            else
            {
                Question++;
            }

            if (Level > 8)
            {
                complete();
                return;
            }
            Test();
        }

        private async void complete()
        {
            string s = "0";
            if (Level <= 8)
            {
                s = DialogUtil.Prompt(this.dialogService, "请输入不通过该组的碰图个数（1-3）", (p) =>
                {
                    if (p != "1" && p != "2" & p != "3")
                        return false;
                    return true;

                }, err.ToString());
            }

            DialogUtil.Show(aggregator, $"通过关数=（{Level-1}）关，本项结束，进入下一项");
            testInfo.data[TestItemIndex].item_score = (int)((double)(Level>8?8:level) * 12.5-s.ToInt()*4) + "";
            this.aggregator.GetEvent<ChangeTestEvent>().Publish(TestItemIndex);
        }

        private async void Test()
        {
            LevelImage = $"pack://application:,,,/Images/g{Level}.png";
            EventInfo info= new EventInfo();
            info.Type = itemType;
            info.Data["img"] = LevelImage;
            info.Data["question"] = $"pack://application:,,,/Images/g{Level}{Question}.png";
            this.aggregator.GetEvent<QuestionChangeEvent>().Publish(info);
        }
    }
}
